export default function supGptCodePlugin(md: any, name: string = 'supgptcode', options?: {
    marker?: string
}) {
    // Second param may be useful if you decide
    // to increase minimal allowed marker length
    function validateDefault(params: any, markup: any) {
        const longName = params.trim().split(' ', 2)[0]
        const indexName = longName.split('-')
        return indexName[0] === name && !!indexName[1] ? {
            name: indexName[0],
            type: indexName[1],
            id: indexName[2]
        } : null;
    }

    function renderDefault(tokens: any, idx: any, _options: any, env: any, slf: any) {
        // console.log('tokens[idx]', tokens[idx])
        const token = tokens[idx]
        return `<${token.tag} data-codeType=${token.codeType} data-codeId=${token.codeId || ''}>${token.content}</${token.tag}>` + token.endContent;
    }

    options = options || {};

    let min_markers = 3,
        marker_str = options.marker || ':',
        marker_char = marker_str.charCodeAt(0),
        marker_len = marker_str.length,
        validate = validateDefault,
        render = renderDefault;

    function container(state: any, startLine: any, endLine: any, silent: any) {
        let pos, nextLine, marker_count, markup, params,
            start = state.bMarks[startLine] + state.tShift[startLine],
            max = state.eMarks[startLine];

        // Check out the first character quickly,
        // this should filter out most of non-containers
        //
        if (marker_char !== state.src.charCodeAt(start)) { return false; }
        // Check out the rest of the marker string
        for (pos = start + 1; pos <= max; pos++) {
            if (marker_str[(pos - start) % marker_len] !== state.src[pos]) {
                break;
            }
        }

        marker_count = Math.floor((pos - start) / marker_len);
        if (marker_count < min_markers) { return false; }
        pos -= (pos - start) % marker_len;

        markup = state.src.slice(start, pos);
        params = state.src.slice(pos, max);
        const vaildRes = validate(params, markup)
        // console.log('11111', vaildRes)
        if (!vaildRes) {
            return false;
        }

        nextLine = startLine;
        let content = '';
        let endContent = '';
        for (; ;) {
            nextLine++;
            if (nextLine >= endLine) {
                break;
            }

            start = state.bMarks[nextLine] + state.tShift[nextLine];
            max = state.eMarks[nextLine];
            const line = state.src.slice(start, max);
            if (start < max && state.sCount[nextLine] < state.blkIndent) {
                // non-empty line with negative indent should stop the list:
                // - ```
                //  test
                // console.log('结束1111', line)
                break;
            }

            if (marker_char !== state.src.charCodeAt(start)) {
                // console.log('continue111________', line)
                content += line + '\n';
                continue;
            }

            if (state.sCount[nextLine] - state.blkIndent >= 4) {
                // closing fence should be indented less than 4 spaces
                // console.log('continue22222________', line)
                content += line + '\n';
                continue;
            }

            for (pos = start + 1; pos <= max; pos++) {
                if (marker_str[(pos - start) % marker_len] !== state.src[pos]) {
                    // console.log('结束22222', line)
                    break;
                }
            }

            // closing code fence must be at least as long as the opening one
            if (Math.floor((pos - start) / marker_len) < marker_count) {
                // console.log('continue33333________', line)
                content += line + '\n';
                continue;
            }

            // make sure tail has spaces only
            pos -= (pos - start) % marker_len;
            pos = state.skipSpaces(pos);

            if (pos < max) {
                // console.log('continue444444________', pos, max, line)
                endContent += '\n' + line.replace(':::', '');
                break;
            }
            break;
        }
        if (!silent) {
            state.line = nextLine + 1;
            const token = state.push(name, name, 0);
            token.content = content.trim();
            token.endContent = endContent.trim();
            token.block = true;
            token.codeType = vaildRes.type;
            token.codeId = vaildRes.id;
        }


        return true;
    }
    md.block.ruler.before('fence', name, container);
    md.renderer.rules[name] = render;
};

export function supGPTCodePlugin(md: any) {
    const parseSupGPTCode = (state: any, startLine: any, endLine: any, silent: any) => {
        let pos = state.bMarks[startLine] + state.tShift[startLine];
        let max = state.eMarks[startLine];
        let line = state.src.slice(pos, max);

        // 检查是否是 ':::' 开始的行
        if (!line.trim().startsWith(':::')) {
            return false;
        }

        // 检查 ':::' 后是否跟随 'supgptcode'
        const parts = line.trim().split(' ');
        if (parts.length < 2 || parts[1] !== 'supgptcode') {
            return false;
        }

        let nextLine = startLine;
        let content = '';
        let foundEnding = false;

        while (nextLine <= endLine) {
            line = state.src.slice(state.bMarks[nextLine], state.eMarks[nextLine]);

            // 检查是否找到 ':::' 结束标记
            if (line.trim() === ':::' && nextLine !== startLine) {
                foundEnding = true;
                break;
            }

            // 添加当前行到内容中
            if (nextLine !== startLine) {
                content += line + '\n';
            }

            nextLine++;
        }

        if (!foundEnding) {
            return false;
        }

        if (!silent) {
            state.line = nextLine + 1;
            const token = state.push('supgptcode', 'supgptcode', 0);
            token.content = content.trim();
            token.block = true;
        }

        return true;
    };

    md.block.ruler.before('fence', 'supgptcode', parseSupGPTCode);

    md.renderer.rules.supgptcode = function (tokens: any, idx: any) {
        return `<supgptcode>${tokens[idx].content}</supgptcode>`;
    };
};